class Solution
{
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target)
    {
        vector<vector<int>> ret;
        int n = nums.size();
        sort(nums.begin(), nums.end());

        for (int i = 0; i < n; i++)
        {
            for (int j = i + 1; j < n; j++)
            {
                long long target2 = (long long)target - nums[i] - nums[j];
                int left = j + 1, right = n - 1;
                while (left < right)
                {
                    if (nums[left] + nums[right] > target2) right--;
                    else if (nums[left] + nums[right] < target2) left++;
                    else
                    {
                        ret.push_back({ nums[i],nums[j],nums[left],nums[right] });
                        while (left + 1 < right && nums[left] == nums[left + 1]) left++;
                        while (left < right - 1 && nums[right] == nums[right - 1]) right--;

                        left++; right--;
                    }
                }
                while (j < n - 1 && nums[j] == nums[j + 1]) j++;
            }
            while (i < n - 1 && nums[i] == nums[i + 1]) i++;
        }
        return ret;
    }
};






